import React, { useRef, useState, useEffect } from 'react';
import { Scroll } from '@/components/Scroll/Scroll';
import { Message} from '@/design';
import { history, useSelector } from 'umi';
import Header from '@/components/Header/Header';
import {isEmpty} from '@/utils/common';
import { queryBraCouponList } from '@/services/coupon';
import Empty from '@/components/Empty/Empty';
import { AffixBottom } from '@/design';
import CouponItem from './couponItem';
import styles from './getCoupon.less';

export default function(props: any){
  const pageNoRef = useRef<number>(1);
  const hasMoreRef = useRef<boolean>(true);
  const { getCouponVisiable } = props;
  const codeId = localStorage.getItem('CODEID');
  const braId = localStorage.getItem('BRAID');

  let userInfo = localStorage.getItem('userInfo');
  const { routerLength } = useSelector((state:any) => state.common);

  const { userId = '' } = JSON.parse(userInfo || '{}');
  const [orderlistDt, setOrderlistDt] = useState<any>({
    couponList: [],
    totalSize: 0,
  });

  useEffect(()=>{
    if(isEmpty(userInfo)) {
      Message.error('請先登入！');
      history.replace('/line')
    }
  }, [])

  useEffect(() => {
    pageNoRef.current = 1;
    hasMoreRef.current = true;
    fetchAllCoupon(true)
  }, [getCouponVisiable])

  /** 請求列表 */
  const fetchAllCoupon = async (refresh: boolean) => {
    if (!hasMoreRef.current) return false;
    let result: any;
    let loading = Message.loading({ content: `正在獲取列表…` });
    result = await queryBraCouponList({
      pageNo: pageNoRef.current,
      braId: localStorage.getItem('BRAID'),
      userId,
      runStatus: 'running',
      plateform: 'fnbqrcode'
    });
    loading.hide();
    if (!result || !result.data) return false;
    pageNoRef.current++;
    setOrderlistDt((prev: any) => {
      let newList = [...(refresh ? [] : prev.couponList), ...result.data.couponList || []]
      hasMoreRef.current = newList.length < result.data.totalSize
      return {
        couponList: newList,
        totalSize: result.data.totalSize,
      }
    })
  }

  const refreshCoupon = async (couponId: string) => {
    const currentIndex = orderlistDt.couponList.findIndex((item:any)=>item.couponId === couponId);
    let tempPageNo =  currentIndex === 0 ? 1 : Math.ceil(currentIndex / 10);
    pageNoRef.current = hasMoreRef.current ? tempPageNo + 1 : tempPageNo;
    let loading = Message.loading({ content: `正在獲取列表…` });
    let result: any;
    result = await queryBraCouponList({
      pageNo: tempPageNo,
      braId: localStorage.getItem('BRAID'),
      userId,
      runStatus: 'running',
      plateform: 'fnbqrcode'
    });
    loading.hide();
    if (!result || !result.data) return false;
   
    let beforeList = orderlistDt.couponList.slice(0, currentIndex);
    const afterListIndex = result.data.couponList.findIndex((item:any)=>item.couponId === couponId);
    let afterList = result.data.couponList.slice(afterListIndex, afterListIndex + 1); //当前最新的
    let lastList = orderlistDt.couponList.slice(currentIndex + 1,  orderlistDt.couponList.length);
    setOrderlistDt(() => {
      hasMoreRef.current =  [...beforeList ,...afterList, ...lastList].length < result.data.totalSize;
      return {
        totalSize: result.data.totalSize,
        couponList: [...beforeList ,...afterList, ...lastList]
      }
    })
  }

  const handleRedirectPath = () => {
    console.log(history)
    if(history.length <= routerLength && history.length < 3) {
      history.push(`/home?braId=${braId}&codeId=${codeId}`)
    } else {
      history.goBack();
    }
  }

  return <>
    <Header hasBack title={'領取優惠券'} onBack={handleRedirectPath}></Header>
    <Scroll hasFooter hasMore={hasMoreRef.current} onPullingUp={fetchAllCoupon}>
      {
      !isEmpty(orderlistDt.couponList) && orderlistDt.couponList.length > 0 ? orderlistDt.couponList.map((item: any, index: number) => {
        return <CouponItem key={`${item.myCouponId}_${index}`} disabled={item['canUse'] === '0' || item['canUse'] === 0} className={styles.coupon} coupon={item} status={status} couponName canGet getCallback={refreshCoupon}/>
      } ) : <Empty/>}
    </Scroll>
    <div className={styles.pay_wrap}>
        <div className={styles.pay_hidden}></div>
        <AffixBottom className={styles.pay_main}>
          <button type="button" className={styles.pay_button} onClick={handleRedirectPath}>完成</button>
        </AffixBottom>
      </div>
  </>
}